<?php

class Controller_Admin_Place extends Controller
{
    public function __construct()
    {
        $aUser = getCurrentUser();
		if (!isset($aUser['utype']) || $aUser['utype'] != 'admin')
		{
		    Controller_Error::forbidden();
		}
    }

	public function edit()
	{
	    $id = isset($this->params[0]) ? intval($this->params[0]) : 0;
	    $place = new Model_Place($id);
	    if (!$id && isset($_GET['sid']))
	    {
	        $place->site_id = intval($_GET['sid']);
	    }
        $aData = $place->values;
	    $errors = array();
	    if (Request::isPost())
	    {
	        $aData = Request::getPost();
    		$validator = new Validator();
    		$validator->add(new Rule_NotEmpty('title', 'Введите название'));
    		$validator->add(new Rule_IntegerPositive('width', 'Введите ширину'));
    		$validator->add(new Rule_IntegerPositive('height', 'Введите высоту'));
            $validator->add(new Rule_IntegerPositive('site_id', 'Выберите сайт'));
    		if ($validator->validate($aData))
    		{
		        if ($id)
		        {
		            $place->save($aData);
		        }
		        else
		        {
		            $place->values = $aData;
    		        $place->save();
		        }
		        Redirect('/admin/site/edit/'.intval($aData['site_id']));
    		}
    		else
    		{
    		    $errors = $validator->errors;
    		}
	    }
	    $aSites = DB::hashedRows('SELECT * FROM sites');
	    
		$this->view->add(array(
		    'id'         => $id,
		    'aData'      => $aData,
		    'aSites'     => $aSites,
		    'errors'     => $errors,
		));
		return $this->view->render('admin/place/edit.tpl');
	}
	

}